import { IModalDetailProps } from '@/types/modal';
import { Modal } from 'antd';
import { useState, useImperativeHandle } from 'react';
import { orderDetail, updateOrderInfo } from '@/api';
import { Order } from '@/types';
import { message } from '@/utils/AntdGlobal';

export default function OrderMark(props: IModalDetailProps) {
  const [visible, setVisible] = useState(false);
  const [orderId, setOrderId] = useState('');
  const [markers, setMarkers] = useState<{ lat: number; lng: number }[]>([]);
  const handleSubmit = async () => {
    const params = {
      orderId: orderId,
      route: markers
    };
    await updateOrderInfo(params);
    message.success('地图打点成功');
    setMarkers([]);
    setVisible(false);
  };
  const handleCancel = () => {
    setVisible(false);
    setMarkers([]);
  };
  useImperativeHandle(props.mRef, () => {
    return {
      open
    };
  });
  const open = async (orderId: string) => {
    setOrderId(orderId);
    setVisible(true);
    const data = await orderDetail(orderId);
    renderMap(data);
  };
  const renderMap = (orderDetail: Order.OrderItem) => {
    const map = new window.BMapGL.Map('markMap');
    const geo = new window.BMapGL.Geocoder();
    const cityName = orderDetail.cityName;
    geo.getPoint(
      cityName,
      point => {
        if (point) {
          map.centerAndZoom(point, 12);
          const scaleCtrl = new window.BMapGL.ScaleControl();
          map.addControl(scaleCtrl);
          const zoomControl = new window.BMapGL.ZoomControl();
          map.addControl(zoomControl);
          orderDetail.route?.map(item => {
            createMark(map, { lat: item.lat, lng: item.lng });
          });
          map.addEventListener('click', function (e) {
            createMark(map, { lat: e.latlng.lat, lng: e.latlng.lng });
          });
        } else {
          console.log('无法获取该城市的坐标信息');
        }
      },
      cityName
    );
  };
  // 创建mark
  const createMark = (
    map: BMapGL.Map,
    point: {
      lat: number;
      lng: number;
    }
  ) => {
    const _marker = new window.BMapGL.Marker(
      new window.BMapGL.Point(point.lng, point.lat)
    );
    // 获取当前 markers 状态
    setMarkers(markers => [...markers, point]);
    const markerMenu = new window.BMapGL.ContextMenu();
    markerMenu.addItem(
      new window.BMapGL.MenuItem('删除', () => {
        // 在删除时更新 markers 状态
        setMarkers(markers => {
          return markers.filter(
            item => item.lat !== point.lat || item.lng !== point.lng
          );
        });
        map.removeOverlay(_marker);
      })
    );
    _marker.addContextMenu(markerMenu);
    map.addOverlay(_marker);
  };

  return (
    <Modal
      title='地图打点'
      width={1100}
      open={visible}
      okText='确定'
      cancelText='取消'
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <div id='markMap' style={{ height: 500 }}></div>
    </Modal>
  );
}
